package view;

import control.Cont_log_sistemaDAO;
import control.Cont_conexao;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import model.Usuario;

public class gui_login extends javax.swing.JFrame {
	
//=========================================================================================
//=========================================================================================
	
	EntityManager gerenciador;
	Query consulta;
	Usuario usuario = new Usuario();
	Cont_conexao rotina = new Cont_conexao();
//	public String usuarioAtual;
	gui_gerencial gerencial = new gui_gerencial();
	
//=========================================================================================

	public gui_login() {
		initComponents();
		this.lbl_menssagem.setText("Entre com o usuário e senha.");
	}//CONSTRUTOR

	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txt_login = new javax.swing.JTextField();
        txt_senha = new javax.swing.JTextField();
        lbl_usuario = new javax.swing.JLabel();
        lbl_senha = new javax.swing.JLabel();
        lbl_menssagem = new javax.swing.JLabel();
        btn_entrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Login");
        setResizable(false);

        txt_login.setText("Administrador");
        txt_login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_loginActionPerformed(evt);
            }
        });

        txt_senha.setText("12345");
        txt_senha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_senhaActionPerformed(evt);
            }
        });

        lbl_usuario.setText("Usuário");

        lbl_senha.setText("Senha");

        lbl_menssagem.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbl_menssagem.setText("Menssagem");

        btn_entrar.setText("Entrar");
        btn_entrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_entrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbl_menssagem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(107, 107, 107)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbl_senha, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lbl_usuario, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txt_senha, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txt_login, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btn_entrar))
                .addContainerGap(112, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(96, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_login, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_usuario))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_senha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_senha))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btn_entrar)
                .addGap(92, 92, 92)
                .addComponent(lbl_menssagem)
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txt_loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_loginActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txt_loginActionPerformed

    private void txt_senhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_senhaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txt_senhaActionPerformed

    private void btn_entrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_entrarActionPerformed
		
		try{
		
			gerenciador = rotina.Conectar();

			consulta = gerenciador.createQuery("select c from Usuario c where c.usuario = :usuario");
			consulta.setParameter("usuario",this.txt_login.getText());
			usuario = (Usuario) consulta.getSingleResult();

			if(usuario.getUsuario().equals(this.txt_login.getText()) && usuario.getSenha().equals(this.txt_senha.getText())){
				
				//Registra LOG no sistema
				//Mensagem de Log
				String log = "Sistema iniciado";
				Cont_log_sistemaDAO dao = new Cont_log_sistemaDAO();
				dao.RegistraLog(usuario, null, log); //Chama o método de LOG passando os dados para serem registrados
				new gui_gerencial().setVisible(true);
				String usu = ""+usuario.getId();
				JOptionPane.showMessageDialog(null, usu);//////////////////////
				gerencial.Configura(usu);
				this.dispose();

			}else{
			
				this.lbl_menssagem.setText("Usuário inválido.");
			
			}//IF

			rotina.Fechar(gerenciador);
			
		}catch(NoResultException a){
			
			this.lbl_menssagem.setText("Usuário inválido");
			
		}catch(Exception b){
		
			JOptionPane.showMessageDialog(null, "Falha na conexão com o banco de dados\n"
										+"A ação não foi realizada, tente novamente.\n"
										+ "Caso esta mensagem percista contate o\n"
										+ "suporte técnico.",
										"Informativo",JOptionPane.INFORMATION_MESSAGE);
			
			this.lbl_menssagem.setText("Falha na conexão com o banco de dados.");
			
		}//TRY CATCH
		
    }//GEN-LAST:event_btn_entrarActionPerformed

	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
		 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Metal".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(gui_login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(gui_login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(gui_login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(gui_login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
        //</editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new gui_login().setVisible(true);
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_entrar;
    private javax.swing.JLabel lbl_menssagem;
    private javax.swing.JLabel lbl_senha;
    private javax.swing.JLabel lbl_usuario;
    private javax.swing.JTextField txt_login;
    private javax.swing.JTextField txt_senha;
    // End of variables declaration//GEN-END:variables
}//CLASS
